# app/services/asr_service.py
import os
import tempfile
from funasr.utils.postprocess_utils import rich_transcription_postprocess
from app.models.asr_model import asr_model_manager
from app.utils.logger import setup_logger

logger = setup_logger("asr_service")

class ASRService:
    @staticmethod
    async def process_audio(audio_data: bytes) -> dict:
        """
        处理音频数据并返回识别结果
        """
        temp_file = None
        try:
            # 将音频数据保存到临时文件
            with tempfile.NamedTemporaryFile(delete=False, suffix='.pcm') as tf:
                temp_file = tf.name
                tf.write(audio_data)
            
            logger.info(f"音频数据已保存到临时文件: {temp_file}, 大小: {len(audio_data)} bytes")
            
            # 获取ASR模型
            model = asr_model_manager.get_model()
            
            # 识别音频
            res = model.generate(
                input=temp_file,
                cache={},
                language="auto",
                use_itn=True,
                batch_size_s=60,
                merge_vad=True,
                merge_length_s=15,
            )
            
            # 处理识别结果
            if res and len(res) > 0:
                text = rich_transcription_postprocess(res[0]["text"])
                logger.info(f"识别结果: {text}")
                return {"status": "success", "type": "final", "text": text}
            else:
                return {"status": "error", "type": "error", "text": "识别结果为空"}
                
        except Exception as e:
            logger.error(f"识别过程中出错: {str(e)}")
            return {"status": "error", "type": "error", "text": f"识别错误: {str(e)}"}
            
        finally:
            # 清理临时文件
            if temp_file and os.path.exists(temp_file):
                try:
                    os.unlink(temp_file)
                    logger.info(f"临时文件已删除: {temp_file}")
                except Exception as e:
                    logger.error(f"删除临时文件失败: {str(e)}")

# 创建服务实例
asr_service = ASRService()